package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.entity.Routes;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class MapUtils {
    public static final String AK = "cKm3D5uftYGqBUaWtOppla2mhGdL4tdE";
    public static final String SK = "MOVuBkmrvAw61FHK42TJQ3dw4bP6m0LM";
    public static final String URL = "https://api.map.baidu.com/directionlite/v1/riding?";

    public static Routes Distance(String origin, String destination) throws Exception {
        Routes routes1 = new Routes();
        origin = roundCoordinate(origin);
        destination = roundCoordinate(destination);
        System.out.println("origin:" + origin);
        System.out.println("destination:" + destination);

        Map<String, String> params = new LinkedHashMap<>();
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("ak", AK);
        String currentTimestamp = String.valueOf(System.currentTimeMillis() / 1000); // 秒级时间戳
        params.put("timestamp", currentTimestamp);
        params.put("sn", caculateSn(origin, destination, currentTimestamp));

        String jsonData = requestGetSN(URL, params);
        JSONObject obj = JSON.parseObject(jsonData);

        if (obj.getIntValue("status") != 0) {
            System.out.println("百度 API 错误: " + obj.getString("message"));
            return null;
        }

        JSONObject result = obj.getJSONObject("result");
        if (result == null) return null;
        JSONArray routes = result.getJSONArray("routes");
        if (routes == null || routes.isEmpty()) return null;

        JSONObject route = routes.getJSONObject(0);
        routes1.setTotalDistance(route.getLong("distance"));
        routes1.setTotalDuration(route.getLong("duration"));

        return routes1;
    }

    private static String caculateSn(String origin, String destination, String timestamp)
            throws Exception {
        Map<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("origin", origin);
        paramsMap.put("destination", destination);
        paramsMap.put("ak", AK);
        paramsMap.put("timestamp", timestamp);

        String paramsStr = toQueryString(paramsMap);
        String wholeStr = "/directionlite/v1/riding?" + paramsStr + SK;
        String encodedWholeStr = URLEncoder.encode(wholeStr, "UTF-8");
        System.out.println("编码后的SN字符串: " + encodedWholeStr);
        return MD5(encodedWholeStr);
    }

    private static String requestGetSN(String strUrl, Map<String, String> param)
            throws Exception {
        if (param == null || param.isEmpty()) return null;

        StringBuilder queryString = new StringBuilder(strUrl);
        for (Map.Entry<String, String> pair : param.entrySet()) {
            queryString.append(pair.getKey()).append("=")
                    .append(UriUtils.encode(pair.getValue(), "UTF-8"))
                    .append("&");
        }
        if (queryString.length() > strUrl.length()) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        URL url = new URL(queryString.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    }

    private static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=")
                    .append(UriUtils.encode((String) pair.getValue(), "UTF-8"))
                    .append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    private static String MD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b & 0xFF));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    private static String roundCoordinate(String coordinate) {
        String[] parts = coordinate.split(",");
        double lat = Double.parseDouble(parts[0]);
        double lng = Double.parseDouble(parts[1]);
        return String.format("%.6f,%.6f", lat, lng);
    }
}